/**
 * mis构建社管基础数据 元数据管理
 *
 */
define(["jquery", "knockout", "durandal/composition", "menu", "durandal/system", "http", "panal", "box", "tree", "slickGrid", "i18nCommon", "view/misbuilder/i18n/i18n", "tabs", "autocomplete",
        "ui", "combotree", "tip", 'selectize', "validate", "koValidate", 'koVCN', 'koExt', 'css!style/misbuilder/css/page-style'
    ],
    function($, ko, composition, menu, system, http, panal, box, tree, Slick, i18nCommon, i18n, tabs,
        autocomplete, ui, combotree, tip, selectize, validate, kov) {

        function model() {
            var self = this;

            kov.init({
                errorShow: 'inBubble',
            }, true);
            var _serviceGetCategoryTableInfo = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/getcategorytableinfo");
            var _serviceGetCategoryTableList = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/getcategorytablelist");
            var _serviceGetTableFieldListByName = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/gettablefieldlistbyname");
            var _serviceAddCategoryTable = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/addcategorytable");
            var _serviceAddCategory = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/savecategoryinfo", { type: "post" });
            var _serviceDeleteCategory = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/deletecategoryinfo", { type: "post" });
            var _serviceSaveCategoryTableInfo = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/savecategorytableinfo", {
                type: "post",
                contentType: 'application/json'
            });
            var _serviceDeleteCategoryTableInfo = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/deletecategorytableinfo", { type: "post" });
            var _serviceRefreshDataMgrSystemMetaData = http.getInstance("/home/datamgr/saveupdate/refreshmetadata");
            var _serviceSaveAddNewTable = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/addnewtable", { type: "post" });
            var _getnewtableinitdata = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/getnewtableinitdata", { type: "GET" });
            var _serviceToEditTable = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/toEditTable", { type: "post" });
            var _addLocationField = http.getInstance("/home/misbuilder/cmbasicdata/basicdatamgr/addLocationFields", { type: "post" });

            self.textAddCategory = "新增类别";
            self.textDeleteCategory = "删除类别";
            self.textEdit = "编辑表";
            self.textSave = i18nCommon.textCommonSaveBtn;
            self.textAdjustOrder = i18n.textAdjustOrder;
            self.textDelete = i18nCommon.textCommonDeleteBtn;
            self.textAdd = i18nCommon.textCommonNewBtn + "元数据表";
            self.textRefresh = i18n.textRefresh;
            self.textAddTable = i18n.textCommonNewTableBtn;

            self.textCmdataCategoryType = i18n.textCmdataCategoryType;
            self.textCmdataType = i18n.textCmdataType;
            self.textCmdataDisplayName = i18n.textCmdataDisplayName;
            self.textCmdataRelatedField = i18n.textCmdataRelatedField;
            self.textCmdataLKeyField = i18n.textCmdataLKeyField;
            self.textCmdataPatrolTableName = i18n.textCmdataPatrolTableName;
            self.textCmdataDBTableID = i18n.textCmdataDBTableID;
            self.textCmdataDBTableName = i18n.textCmdataDBTableName;
            self.textCmdataIfMarkMap = i18n.textCmdataIfMarkMap;
            self.textCmdataIfMustMarkMap = i18n.textCmdataIfMustMarkMap;
            self.textCmdataIfCrud = i18n.textCmdataIfCrud;
            self.textCmdataIfExcelImport = i18n.textCmdataIfExcelImport;
            self.textCmdataIfDisplay = i18n.textCmdataIfDisplay;
            self.textCmdataGetField = i18n.textCmdataGetField;
            self.textCmdataGetLocationField = "添加地图定位字段";

            self.textCmdataFieldName = i18n.textCmdataFieldName;
            self.textCmdataFieldType = i18n.textCmdataFieldType;
            self.textCmdataFieldId = i18n.textCmdataFieldId;
            self.textCmdataNullable = i18n.textCmdataNullable;
            self.textCmdataQueryField = i18n.textCmdataQueryField;
            self.textCmdataListField = i18n.textCmdataListField;
            self.textCmdataSortField = i18n.textCmdataSortField;
            self.textCmdataRefreshDataMgrSystem = i18n.textCmdataRefreshDataMgrSystem;
            self.textCmdataRefreshCache = i18n.textCmdataRefreshCache;
            self.textCmdataDicIfKey = i18n.textCmdataDicIfKey;
            self.textColumnDataLength = i18n.textColumnDataLength;
            //self.textCmdataAddField = i18n.textCmdataAddField;

            var yesOrNo = [
                { 'flag': '0', 'text': '否' },
                { 'flag': '1', 'text': '是' }
            ];
            var cmTypes = [
                { 'cmTypeID': '0', 'cmTypeName': '' },
                { 'cmTypeID': '1', 'cmTypeName': '人' },
                { 'cmTypeID': '99', 'cmTypeName': '其他' }
            ];
            self.categories = ko.observableArray();
            self.cmTypes = ko.observableArray(cmTypes);
            self.tableFieldNames = ko.observableArray();
            self.ifMarkMap = ko.observableArray(yesOrNo);
            self.ifMustMarkMap = ko.observableArray(yesOrNo);
            self.ifExcelImport = ko.observableArray(yesOrNo);
            self.ifDisplay = ko.observableArray(yesOrNo);
            self.ifCrud = ko.observableArray(yesOrNo);
            self.tableId = ko.observable();
            self.metaDataCategoryId = ko.observable();
            self.cmTypeID = ko.observable();
            self.tableName = ko.observable().extend({ maxLength: 40 }).extend({ minLength: 4 });
            self.newtableName = ko.observable().extend({ maxLength: 40 }).extend({ minLength: 4 });
            self.displayName = ko.observable().extend({ maxLength: 80 }).extend({ minLength: 2 });
            self.tableDesc = ko.observable();
            self.primaryKeyFieldName = ko.observable();
            //.extend({trim:''}).extend({ required: true }).extend({ maxLength:80 });
            self.relatedFieldName = ko.observable('-1');
            self.tcPatrolTableName = ko.observable();
            self.isUseMap = ko.observable();
            self.isDisplay = ko.observable();
            self.importFlag = ko.observable("1");
            self.isMustMarkMap = ko.observable();
            self.editFlag = ko.observable("1");
            self.btnVisiable = ko.observable(false);
            self.btnVisiable2 = ko.observable(false);
            self.btnVisiable3 = ko.observable(false);
            self.btnVisiable4 = ko.observable(false);
            self.btnTableVisiable = ko.observable(false);
            self.columnType = ko.observableArray([{ columnTypeSelectID: "1", columnTypeSelectName: "INTEGER" }, { columnTypeSelectID: 2, columnTypeSelectName: "VARCHAR2" }, { columnTypeSelectID: 3, columnTypeSelectName: "DATE" }, { columnTypeSelectID: 4, columnTypeSelectName: "NUMBER" }]);

            var _tabTable;
            var _tabCategory;
            var _tab = 'newTableColumn';
            var _row = -1;
            var _i = 0;
            var _categoryID;
            var _newAddTableFlag = false;
            var _tablename;
            /**搜索框自动完成需要的业务表列表信息*/
            var _tableList;

            /**对树结构的引用*/
            var _tableTree;

            var columns = [
                { id: "index", name: "序号", field: "index", sortable: true, width: 60 },
                { id: "tableId", name: "标识", field: "tableId", sortable: true, width: 60 },
                { id: "tableName", name: "表名", field: "tableName", sortable: true, width: 160 },
                { id: "displayName", name: "展示名称", field: "displayName", sortable: true, width: 160 },
                { id: "primaryKeyFieldName", name: "主键", field: "primaryKeyFieldName", sortable: true, width: 100 },
                { id: "relatedFieldName", name: "关联建", field: "relatedFieldName", sortable: true, width: 100 },
                { id: "tcPatrolTableName", name: "采集表名称", field: "tcPatrolTableName", sortable: true, width: 180 }
            ];
            var options = {
                enableCellNavigation: true,
                enableColumnReorder: false,
                multiSelect: false,
                forceFitColumns: true
            };
            /**存储当前活动的业务表信息*/
            var _table = ko.pureComputed({
                read: function() {
                    return {
                        tableId: self.tableId(),
                        metaDataCategoryId: self.metaDataCategoryId(),
                        cmTypeID: self.cmTypeID(),
                        tableName: self.tableName(),
                        displayName: self.displayName(),
                        tableDesc: self.displayName(),
                        primaryKeyFieldName: "PID",
                        relatedFieldName: self.relatedFieldName(),
                        tcPatrolTableName: self.tableName(),
                        isUseMap: self.isUseMap(),
                        isDisplay: 1,
                        importFlag: self.importFlag(),
                        isMustMarkMap: self.isUseMap(),
                        editFlag: self.editFlag(),
                        newtableName: self.newtableName()
                    };
                },
                write: function(u) {
                    self.tableId(u.tableId);
                    self.metaDataCategoryId(u.metaDataCategoryId);
                    self.cmTypeID(u.cmTypeID);
                    self.tableName(u.tableName);
                    self.displayName(u.displayName);
                    self.tableDesc(u.displayName);
                    self.primaryKeyFieldName(u.primaryKeyFieldName);
                    self.relatedFieldName(u.relatedFieldName);
                    self.tcPatrolTableName(u.tableName);
                    self.isUseMap(u.isUseMap);
                    self.isDisplay(u.isDisplay);
                    self.importFlag(u.importFlag);
                    self.isMustMarkMap(u.isUseMap);
                    self.editFlag(u.editFlag);
                    self.newtableName(u.newtableName);

                },
                owner: this
            });


            composition.addBindingHandler("metadatatableInit", {
                init: function(dom) {
                    self._dom = model._dom = $(dom);
                    initUI();
                    bindUI();
                }
            });


            /**
             * 初始化界面
             */
            function initUI() {
                _tableTree = $("#misbuilder-metadatatable-tree");

                _tabCategory = tabs.getInstance([{
                    id: 1,
                    title: "业务表",
                    content: self._dom.find('.misbuilder-metadatacategory-info'),
                    selected: true
                        // },
                        // {
                        //     id: 2,
                        //     title: "新建表",
                        //     content: self._dom.find('.misbuilder-metadatanewtable-info'),
                        //     selected: false
                }], {
                    parent: self._dom.find('.misbuilder-common-info-container'),
                    headRight: 0,
                    width: '100%',
                    height: 500,
                    contentBorder: false,
                    onSelect: function(tabId, title) {
                        if (tabId == 1) {
                            self._dom.find('.misbuilder-metadatacategory-info').css('display', 'block');
                            self._dom.find('.misbuilder-metadatanewtable-info').css('display', 'none');
                            self.btnTableVisiable(false);
                        } else if (tabId == 2) {
                            self._dom.find('.misbuilder-metadatacategory-info').css('display', 'none');
                            self._dom.find('.misbuilder-metadatanewtable-info').css('display', 'block');
                            self.btnTableVisiable(true);
                            _i++;
                            if (_i == 1) {
                                loadTableColumn(_tab, _row);
                            }
                        }
                    },
                    onClose: function(tabId, title) {}
                });
                _tabTable = tabs.getInstance([{
                    id: "misbuilder-metadatatable-tab",
                    title: "基本属性",
                    content: $("#misbuilder-metadatatable-info"),
                    selected: true,
                }], {
                    parent: $("#misbuilder-metadatatable-info-container"),
                    contentBorder: false,
                    onSelect: function(tabId, title) {},
                    onClose: function(tabId, title) {},
                    width: '100%',
                    height: 500,
                });
                loadTableTree();

                /* 初始化业务表列表 */
                self._tableTs = new Slick.Grid("#misbuilder-metadatacategory-tableList", [], columns, options);
                self._tableTs.setSelectionModel(new Slick.RowSelectionModel());
                self._tableTs.registerPlugin(new Slick.AutoTooltips({
                    enableForHeaderCells: true
                }));
            }

            function bindUI() {
                $(".cm-all-null-check").on("change", function() {
                    self.nullAllCheck();
                });
                $(".cm-all-query-check").on("change", function() {
                    self.queryAllCheck();
                });
                $(".cm-all-list-check").on("change", function() {
                    self.listAllCheck();
                });

            }

            function loadTableColumn(tab, row) {
                _getnewtableinitdata.ajax({}).then(function(data) {
                    var columnDataInit = data.columnInitData;
                    var nullAble = "";
                    var primaryAble = "";
                    for (var i = 0; i < columnDataInit.length; i++) {
                        if (columnDataInit[i].nullAble == 1) {
                            nullAble = 'checked';
                        }
                        if (columnDataInit[i].primaryAble == 1) {
                            primaryAble = 'checked';
                        }

                        var trHtmlInit = "<tr align='center'><td ><input type='checkbox' name='ckb'/></td>" +
                            "<td ><input value='" + columnDataInit[i].columnName + "' disabled='disabled'></td>" +
                            "<td ><input value='" + columnDataInit[i].dataType + "' disabled='disabled'></td>" +
                            "<td ><input value='" + columnDataInit[i].dataLength + "' disabled='disabled'></td>" +
                            "<td ><input type='checkbox' " + nullAble + "='" + nullAble + "'></td>" +
                            "<td ><input type='radio' " + primaryAble + "='" + primaryAble + "'></td></tr>";
                        addTr(tab, row, trHtmlInit);
                    }
                });
            }
            /**
             * 加载类别业务表树
             */
            function loadTableTree() {
                _tableTree.tree({
                    url: eUrban.global.rootPath + "home/misbuilder/cmbasicdata/basicdatamgr/catgorytabletree",
                    dnd: false,
                    onBeforeLoad: function() {
                        showTip("loading", i18nCommon.textCommonDataLoading);
                    },
                    onLoadSuccess: function(node) {
                        closeTip();
                        if (self.tableId()) {
                            _tableTree.tree("select", _tableTree.tree("find", self.tableId()).target);
                        } else if (self.metaDataCategoryId() && self.metaDataCategoryId() != -1) {
                            _tableTree.tree("select", _tableTree.tree("find", self.metaDataCategoryId()).target);
                        } else {
                            var rootNode = _tableTree.tree("getRoot");
                            if (rootNode) {
                                _table("");
                                _tableTree.tree("select", rootNode.target);
                            }
                        }
                    },
                    onSelect: function(node) {
                        closeTip();
                        if ("icon-table" === node.iconCls) { //点击三级节点
                            _tablename = node.attributes.tableName;
                            self.tableId(node.id);
                            categoryTableSelected(node.id);
                        } else { //点击一二级节点
                            _categoryID = node.id;
                            catgorySelected(node.id);
                        }
                    },
                });
            }


            //点击类别节点触发
            function catgorySelected(categoryID) {
                _tabTable.hide();
                _tabCategory.show();
                self.btnVisiable(false);
                self.btnVisiable4(false);
                if (categoryID == -1) {
                    self.btnVisiable3(true);
                    self.btnVisiable2(false);
                } else {
                    self.btnVisiable2(true);
                    self.btnVisiable3(false);
                }
                showTip("loading", i18nCommon.textCommonDataLoading);
                _serviceGetCategoryTableList.ajax({ "categoryID": categoryID }).then(function(data) {
                    //渲染表格
                    var index = 1;
                    $(data.categoryTableList).each(function() {
                        this.index = index++;
                    });
                    self._tableTs.setData(data.categoryTableList);
                    self._tableTs.setSelectedRows([]);
                    self._tableTs.render();

                    //初始化搜索框
                    if (categoryID == "-1") {
                        _tableList = data.categoryTableList;
                        self._maxTableID = getMaxTableID(_tableList)+1;
                        refreshSearchInfo();
                    }
                    closeTip();
                }, this).error(function() {
                    closeTip();
                });
            }
            
            function getMaxTableID(tableList){
            	var maxTableID = 0;
            	for(var i=0;i<tableList.length;i++){
            		if(tableList[i].tableId > maxTableID){
            			maxTableID = tableList[i].tableId;
            		}
            	}
            	return maxTableID;
            }

            //点击表单节点触发
            function categoryTableSelected(tableID) {
                _tabCategory.hide();
                _tabTable.show();
                self.btnVisiable(true);
                self.btnVisiable2(false);
                self.btnVisiable3(false);
                self.btnVisiable4(true);
                self.btnTableVisiable(false);
                showTip("loading", i18nCommon.textCommonDataLoading);
                resetTableFieldList();
                setCategories();
                var categoryID = _tableTree.tree("getParent", _tableTree.tree("getSelected").target).id;
                _serviceGetCategoryTableInfo.ajax({ "categoryID": categoryID, "tableID": tableID }).then(function(data) {
                    //字段信息
                    if (null != data.tableFieldList && data.tableFieldList.length > 0) {
                        self.tableFieldList = data.tableFieldList;
                        fillTableFieldList(data.tableFieldList);
                    }

                    //基本信息
                    if (null != data.tableInfo) {
                        _table(data.tableInfo);
                        self.tableInfo = data.tableInfo;
                    }

                    closeTip();
                }, this).error(function() {
                    closeTip();
                });
            }

            //填充表字段信息
            function fillTableFieldList(tableFieldList) {
                var tableFieldNames = [];
                var adjustOrderHtml = ["<div class='cm-data-order-toolbar'>",
                    "<div class='down-bottom' title='置底' movetype='down-bottom'></div>",
                    "<div class='up-top' title='置顶' movetype='up-top'></div>",
                    "<div class='down-one' title='向下' movetype='down-one'></div>",
                    "<div class='up-one' title='向上' movetype='up-one'></div>",
                    "</div>"
                ].join("");
                for (var i = 0; i < tableFieldList.length; i++) {
                    var htmlText = [];
                    htmlText.push("<tr class='cm-data-field' id='field_" + tableFieldList[i].fieldName + "'>");
                    htmlText.push("<td><input type='text' class='textbox' id='fieldName_" + tableFieldList[i].fieldName + "' value='" + tableFieldList[i].fieldName + "' disabled /></td>");
                    htmlText.push("<td><input type='text' class='textbox' id='disName_" + tableFieldList[i].fieldName + "' value='" + (tableFieldList[i].displayName != 'null' ? tableFieldList[i].displayName : tableFieldList[i].fieldName) + "' /></td>");
                    htmlText.push("<td><input type='text' class='textbox' id='dtName_" + tableFieldList[i].fieldName + "' value='" + tableFieldList[i].dataTypeName + "' disabled /></td>");
                    htmlText.push("<input type='hidden' class='textbox' id='fieldId_" + tableFieldList[i].fieldName + "' value='" + tableFieldList[i].fieldId + "' disabled />");
                    if (1 == tableFieldList[i].nullFlag) {
                        htmlText.push("<td><input  checked  type='checkbox'  id='nullFlag_" + tableFieldList[i].fieldName + "'>");
                    } else {
                        htmlText.push("<td><input   type='checkbox'  id='nullFlag_" + tableFieldList[i].fieldName + "'>");
                    }
                    if (1 == tableFieldList[i].queryFieldFlag) {
                        htmlText.push("<td><input checked type='checkbox' id='queryFieldFlag_" + tableFieldList[i].fieldName + "'>");
                    } else {
                        htmlText.push("<td><input   type='checkbox' id='queryFieldFlag_" + tableFieldList[i].fieldName + "'>");
                    }
                    if (1 == tableFieldList[i].listFieldFlag) {
                        htmlText.push("<td><input checked type='checkbox' id='listFieldFlag_" + tableFieldList[i].fieldName + "'>");
                    } else {
                        htmlText.push("<td><input   type='checkbox' id='listFieldFlag_" + tableFieldList[i].fieldName + "'>");
                    }
                    htmlText.push("<input    type='hidden'  id='dataTypeId_" + tableFieldList[i].fieldName + "' value='" + tableFieldList[i].dataTypeId + "'/>");
                    htmlText.push("<td>" + adjustOrderHtml + "</td>");
                    htmlText.push("</tr>");
                    $("#categoryTableFieldList").append(htmlText.join(""));

                    if(tableFieldList[i].fieldName != "PID"){
                    	tableFieldNames.push(tableFieldList[i].fieldName);
                    };
                }
                //字段关联中，在头部加入空值选项
                tableFieldNames.unshift("");
                //字段排序
                $("#categoryTableFieldList").find("div[movetype]").off("click").on("click", function() {
                    var fieldObjList = $("#categoryTableFieldList").find(".cm-data-field");
                    var moveObj = $(this).parent().parent().parent();
                    var movetype = $(this).attr("movetype");
                    var targetObj;
                    switch (movetype) {
                        case 'down-bottom':
                            targetObj = fieldObjList.eq(fieldObjList.length - 1);
                            break;
                        case 'up-top':
                            targetObj = fieldObjList.eq(0);
                            break;
                        case 'down-one':
                            targetObj = moveObj.next();
                            break;
                        case 'up-one':
                            targetObj = moveObj.prev();
                            break;
                        default:
                            return;
                    }
                    if (targetObj && targetObj.prop("id") && targetObj.prop("id") != moveObj.prop("id") &&
                        targetObj.prop("id").indexOf("field_") > -1) {
                        var obj = moveObj.clone(true);
                        moveObj.remove();
                        if (movetype.indexOf("down-") > -1) {
                            targetObj.after(obj);
                        } else if (movetype.indexOf("up-") > -1) {
                            targetObj.before(obj);
                        }
                    }
                });
                self.tableFieldNames(tableFieldNames);
            }

            //清除表字段列表信息
            function resetTableFieldList() {
                self.tableFieldList = null;
                self.tableInfo = null;
                $("#categoryTableFieldList").find("tr").each(function() {
                    if ($(this).attr("id") && $(this).attr("id").indexOf("field_") > -1) {
                        $(this).remove();
                    }
                });
            }

            //获取表字段信息
            function getTableFieldListByName(tableName) {
                if (!validateTableName(tableName)) return;
                showTip("loading", i18nCommon.textCommonDataLoading)
                _serviceGetTableFieldListByName.ajax({ "tableName": tableName }).then(function(data) {
                    closeTip();
                    if (0 == data.validFlag) {
                        var categoryNode = _tableTree.tree("getSelected");
                        categoryNode.nowTableName = $("#nowTableName").val();
                        categoryNode.cmTypeID = self.cmTypeID();
                        var b1 = box.confirm("该表" + tableName + "在数据库中不存在,是否需要创建表" + tableName + "?", "消息", {
                            clickYes: function() {
                                var addTablePanal = panal.getInstance("view/misbuilder/cmbasicdata/addtable", {
                                    width: 1000,
                                    height: 540,
                                    title: "新建表",
                                    minBtn: false,
                                    contentOpacity: 1,
                                    modal: true,
                                    resizable: false
                                }, { data: categoryNode });
                                addTablePanal.settings.onClose = function(){
                                	getTableFieldListByName(self.tableName());
                                }
                            },
                            clickNo: function() {}
                        });
                    }

                    resetTableFieldList();
                    //填充字段信息
                    if (null != data.tableFieldList && data.tableFieldList.length > 0) {
                        self.tableFieldList = data.tableFieldList;
                        fillTableFieldList(data.tableFieldList);
                    }
                });
            }

            /**
             * 更新搜索框信息
             */
            function refreshSearchInfo() {
                if (null != _tableList && _tableList.length > 0) {
                    $("#misbuilder-metadatatable-search").autocomplete(_tableList, {
                        minChars: 0,
                        width: 213,
                        matchContains: true,
                        scroll: true,
                        scrollHeight: 160,
                        selectFirst: true,
                        formatMatch: function(row, i, max) {
                            return row.displayName + row.tableName + row.tableId;
                        },
                        formatItem: function(row, i, max) {
                            return row.displayName + "(" + row.tableName + ")" + "(" + row.tableId + ")";
                        },
                        formatResult: function(row) {
                            return row.displayName + "(" + row.tableName + ")" + "(" + row.tableId + ")";
                        }
                    });

                    $("#misbuilder-metadatatable-search").flushCache();

                    $("#misbuilder-metadatatable-search").result(function(event, data, formatted) {
                        if (null == _tableTree.tree("find", data.tableId)) {
                            expandTableTree(data.tableId);
                        } else {
                            _tableTree.tree("expandTo", _tableTree.tree("find", data.tableId).target);
                            _tableTree.tree("select", _tableTree.tree("find", data.tableId).target);
                            _tableTree.tree("find", data.tableId).target.scrollIntoView(false);
                        }
                    });
                }
            }

            function expandTableTree(TableID) {

            }

            /**
             * 验证表名
             */
            function validateTableName(tableName) {
                var validFlag = true;
                var str = /^[A-Za-z]*$/;
                var reg = /^[0-9a-zA-Z]+$/;
                if (null == tableName || "" == tableName.replace(/^\s+|\s+$/g, "") || tableName.indexOf(".") < 0) {
                    showTip("error", "请输入正确的数据库表名称（oracle版本带表空间）！");
                    return false;
                } else {
                    var tableNameSplit = tableName.split(".");
                    if (tableNameSplit.length == 2 && str.test(tableNameSplit[0]) && str.test(tableNameSplit[1][0]) && reg.test(tableNameSplit[1].replace(/_/g, ''))) {} else {
                        showTip("error", "请输入正确的数据库表名称（oracle版本带表空间）！");
                        return false;
                    }
                }

                var rootNode = _tableTree.tree("getRoot");
                var childrenNodes = _tableTree.tree('getChildren', rootNode.target);
                $(childrenNodes).each(function() {
                    if ("icon-table" == this.iconCls) {
                        if (this.attributes.tableName.toLowerCase() == tableName.toLowerCase() &&
                            this.id != self.tableId()) {
                            validFlag = false;
                            showTip("error", "该表已配置,请更换表名！");
                            return;
                        }
                    }
                });
                return validFlag;
            }

            /**
             * 设置类别列表
             */
            function setCategories() {
                self.categories.removeAll();
                var rootNode = _tableTree.tree("getRoot");
                var childrenNodes = _tableTree.tree('getChildren', rootNode.target);
                $(childrenNodes).each(function() {
                    if ("icon-category" == this.iconCls) {
                        self.categories.push({ 'categoryID': this.id, 'categoryName': this.text });
                    }
                });
            }

            function getNextFieldId() {
                var fieldIds = [];
                $("#categoryTableFieldList input[type='hidden']").each(function() {
                    if ($(this).attr("id") && $(this).attr("id").indexOf("fieldId_") > -1) {
                        fieldIds.push($(this).val())
                    }
                });
                return Number(fieldIds.sort()[fieldIds.length - 1]) + 1;
            }

            function showTip(type, message) {
                if (type === "success") {
                    tip.showSuccess(message, 10, 10, $("#misbuilder-metadatatable-buttons"));
                } else if (type === "loading") {
                    tip.showLoading(message, 10, 10, $("#misbuilder-metadatatable-buttons"));
                } else if (type === 'error') {
                    tip.showError(message, 10, 10, $("#misbuilder-metadatatable-buttons"));
                }
            }

            function closeTip() {
                tip.closeTip($("#misbuilder-metadatatable-buttons"));
            }

            /**
             * 刷新
             */
            self.refresh = function() {
                _tableTree.tree("reload");
            }

            self.getField = function() {
                if(self.cmTypeID() != 0){
                	getTableFieldListByName(self.tableName());
                }else{
                	box.alert("请选择综治数据类型！");
                	self._dom.find("#cmTypes").focus();
                }
            }

            // 添加地图定位信息字段
            self.addLocationField = function() {
                var tableName = $("#nowTableName").val();
                var params = { tableName: tableName };
                _addLocationField.ajax(params).then(function(data) {
                	self.getField();
                }).error(function(data, result) {
                    box.alert(result.message);
                });
            }


            /**
             * 新建类别
             */
            self.addCategory = function() {
                var seniorId;
                var selectedNode = _tableTree.tree("getSelected");
                if ("icon-root" == _tableTree.tree("getSelected").iconCls) {
                    seniorId = -1;
                } else if ("icon-category" == _tableTree.tree("getSelected").iconCls) {
                    seniorId = _tableTree.tree("getSelected").id;
                } else if ("icon-table" == _tableTree.tree("getSelected").iconCls) {
                    seniorId = _tableTree.tree("getParent", _tableTree.tree("getSelected").target).id;
                } else {
                    return;
                }
                box.prompt('输入类别名称', '新建类别', {
                    clickSure: function(value) {
                        //判断类别名是否已经存在
                        var temp = new Array();
                        for (var i = 0; i < selectedNode.children.length; i++) {
                            temp.push(selectedNode.children[i].text);
                        }
                        if ($.inArray(value, temp) != -1) {
                            var b1 = box.confirm("类别已存在！", "消息", {
                                clickYes: function() {},
                                clickNo: function() {}
                            });
                        } else {
                            _serviceAddCategory.ajax({
                                metaDataCategoryName: value,
                                seniorId: seniorId
                            }).then(function(data) {
                                showTip("success", "添加类别成功！")
                                self.refresh();
                            });
                        }

                    }
                }, '#misbuilder-metadatatable-content');


            }

            /**
             * 删除类别
             */
            self.deleteCategory = function() {
                var selectedNode = _tableTree.tree("getSelected");
                if (selectedNode && selectedNode.iconCls == "icon-category") {
                    var b1 = box.confirm("确认要删除类别[" + selectedNode.text + "]及[" + selectedNode.text + "]下面的所有表吗？", "消息", {
                        clickYes: function() {
                            var param = {
                                "categoryID": selectedNode.id
                            };
                            _serviceDeleteCategory.ajax(param).then(function(data) {
                                if (data) {
                                    var categoryNode = _tableTree.tree("getParent", _tableTree.tree("getSelected").target);
                                    _tableTree.tree("select", categoryNode.target);
                                    _table("");
                                    self.tableFieldNames.removeAll();
                                    resetTableFieldList();
                                    self.refresh();
                                }
                            });
                        },
                        clickNo: function() {}
                    });
                }
            }

            /**
             * 新增表
             */
            self.addTable = function() {
            	self.tableId(self._maxTableID);
            	_newAddTableFlag = true;
                var categoryNode;
                if ("icon-category" == _tableTree.tree("getSelected").iconCls) {
                    categoryNode = _tableTree.tree("getSelected");
                } else if ("icon-table" == _tableTree.tree("getSelected").iconCls) {
                    categoryNode = _tableTree.tree("getParent", _tableTree.tree("getSelected").target);
                } else {
                    return;
                }
//                _table({tableId:self._maxTableID,tableName:"dldata.tccmdata"+self._maxTableID, displayName:"新建表"+self._maxTableID});
                self.tableId(self._maxTableID);
                self.tableName("dldata.tccmdata"+self._maxTableID);
                self.displayName("新建表"+self._maxTableID);
                _tabCategory.hide();
                _tabTable.show();
                self.btnVisiable(true);
                self.btnVisiable4(false);
                self.btnVisiable2(false);
                self.btnVisiable3(false);
                self.btnTableVisiable(false);

                resetTableFieldList();
                //把基本信息设置为当前表信息
                self.categories.removeAll();
                self.categories.push({ 'categoryID': categoryNode.id, 'categoryName': categoryNode.text });
                $("#tcPatrolTableName").val('');
                self.tableFieldNames.removeAll();
            }
            /**
             * 修改表结构
             */
            self.editTable = function() {
                self.btnVisiable4(true);
                toEditTable(_tablename);
            }

            function toEditTable(tableName) {
                var tableName = $("#nowTableName").val();
                _serviceToEditTable.ajax({ "tableName": tableName }).then(function(data) {
                	data.cmTypeID = self.cmTypeID();
                    panal.getInstance("view/misbuilder/cmbasicdata/edittable", {
                        width: 1000,
                        height: 540,
                        title: "修改表结构",
                        minBtn: false,
                        contentOpacity: 1,
                        modal: true,
                        resizable: false
                    }, { data: data });
                });
            }

            /**
             * 删除表
             */
            self.del = function() {
                if (_tableTree.tree("getSelected").iconCls == "icon-table") {
                    var b1 = box.confirm("确认要删除表[" + self.displayName() + "]吗？", "消息", {
                        clickYes: function() {
                            var tableID = self.tableId();
                            var param = {
                                "tableID": tableID
                            };
                            _serviceDeleteCategoryTableInfo.ajax(param).then(function(data) {
                                if (data) {
                                    var categoryNode = _tableTree.tree("getParent", _tableTree.tree("getSelected").target);
                                    _tableTree.tree("select", categoryNode.target);
                                    _table("");
                                    self.tableFieldNames.removeAll();
                                    resetTableFieldList();
                                    self.refresh();
                                }
                            });
                        },
                        clickNo: function() {}
                    });
                }
            }

            /**
             * 保存
             */
            self.save = function() {
            	if(self.cmTypeID() == 0){
                	box.alert("请选择综治数据类型！");
                	self._dom.find("#cmTypes").focus();
                	return;
                }
                self.btnVisiable4(true);
                if (!kov.submit($('#misbuilder-metadatatable-content'))) {
                    return false;
                }
                var metaDataFieldList = [];
                var orderIndex = Number(self.tableId()) * 100 + 1;
                $("#categoryTableFieldList").find("tr").each(function() {
                    if ($(this).attr("id") && $(this).attr("id").indexOf("field_") > -1) {
                        var fieldName = $(this).attr("id").replace("field_", "");

                        var fieldInfo = {
                            "tableId": self.tableId(),
                            "fieldName": $("#fieldName_" + fieldName).val(),
                            "displayName": $("#disName_" + fieldName).val(),
                            "dataTypeName": $("#dtName_" + fieldName).val(),
                            "fieldId": $("#fieldId_" + fieldName).val(),
                            "relatedFieldFlag": (self.relatedFieldName() == fieldName ? 1 : 0),
                            "primaryKeyFieldFlag": ("PID" == fieldName ? 1 : 0),
                            "nullFlag": $("#nullFlag_" + fieldName).is(':checked') == true ? 1 : 0,
                            "queryFieldFlag": $("#queryFieldFlag_" + fieldName).is(':checked') == true ? 1 : 0,
                            "listFieldFlag": $("#listFieldFlag_" + fieldName).is(':checked') == true ? 1 : 0,
                            "dataTypeId": $("#dataTypeId_" + fieldName).val(),
                            "displayOrder": orderIndex++
                        };

                        if (self.tableFieldList != null) {
                            $(self.tableFieldList).each(function(index) {
                                if (this.fieldId.toString() == fieldInfo.fieldId.toString()) {
                                    for (var key in this) {
                                        if (key in fieldInfo) {} else {
                                            fieldInfo[key] = this[key]; //其他未编辑字段值
                                        }
                                    }
                                }
                            });
                        }

                        metaDataFieldList.push(fieldInfo);
                    }
                });

                if (self.relatedFieldName == "-1") {
                    showTip("error", "关联字段不能为空!");
                    return;
                }
                var param = {};
                param.table = _table();
                if (null != self.tableInfo) {
                    for (var key in self.tableInfo) {
                        if (key in param.table) {} else {
                            param.table[key] = self.tableInfo[key]; //其他未编辑字段值
                        }
                    }
                }
                param.table.tableId = self.tableId();
                param.metaDataFieldList = metaDataFieldList;
                if ($("#displayName").val() == "") {
                    var b1 = box.confirm("显示名称不能为空!", "消息", {
                        clickYes: function() {},
                        clickNo: function() {}
                    });
                } else {
                    showTip("loading", "保存中...");
                    _serviceSaveCategoryTableInfo.ajax(JSON.stringify(param)).then(function(data) {
                        catgorySelected(_categoryID);
                        showTip("success", "保存成功！");
                        //刷新数据在线采集元数据配置信息的缓存
                        _serviceRefreshDataMgrSystemMetaData.ajax().then(function() {});
                        self.refresh();
                        if(_newAddTableFlag){
                        	self._maxTableID++;
                        	_newAddTableFlag = false;
                        }
                    }).error(function(data) {
                        showTip("error", data.errorMsg);
                    });
                }
            }


            //可否为空全选事件
            self.nullAllCheck = function() {
                var isChecked = $(".cm-all-null-check").prop("checked");
                $(".cm-data-fieldlist-table").find(":checkbox").each(function() {
                    if ($(this).attr("id") && $(this).attr("id").indexOf("nullFlag_") > -1) {
                        $(this).prop("checked", isChecked);
                    }
                });
            }

            //列表字段全选事件
            self.listAllCheck = function() {
                var isChecked = $(".cm-all-list-check").is(":checked")
                $(".cm-data-fieldlist-table").find(":checkbox").each(function() {
                    if ($(this).attr("id") && $(this).attr("id").indexOf("listFieldFlag_") > -1) {
                        $(this).prop("checked", isChecked);
                    }
                });
                $(".cm-all-list-check").attr("checked", isChecked);
            }

            //查询字段全选事件
            self.queryAllCheck = function() {
                var isChecked = $(".cm-all-query-check").is(":checked")
                $(".cm-data-fieldlist-table").find(":checkbox").each(function() {
                    if ($(this).attr("id") && $(this).attr("id").indexOf("queryFieldFlag_") > -1) {
                        $(this).prop("checked", isChecked);
                    }
                });
            }

            self.resize = function() {
                if ($(".cm-data-fieldlist").attr("state") != "big") {
                    $(".cm-data-fieldlist").animate({ top: '0px', height: "450px" });
                    $(".cm-data-fullscreen").removeClass("glyphicon-resize-full").addClass("glyphicon-resize-small");
                    $(".cm-data-fieldlist").prop("title", "缩小");
                    $(".cm-data-fieldlist").attr("state", "big");
                } else {
                    $(".cm-data-fieldlist").animate({ top: '180px', height: "250px" });
                    $(".cm-data-fullscreen").removeClass("glyphicon-resize-small").addClass("glyphicon-resize-full");
                    $(".cm-data-fieldlist").prop("title", "放大");
                    $(".cm-data-fieldlist").attr("state", "small");
                }

            }
        }
        model._dom = null;
        return model;
    });